import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useSessionEditorStore } from './sessionEditor'
import { DialogQueue } from '@/utils/dialogQueue'
import { agencyAsync, AppoxSessionIdentifier } from '@/appox/appox'

export const useSessionListStore = defineStore('sessionList', () => {
  const sessionEditorStore = useSessionEditorStore()
  
  // 状态
  const dialogQueue = new DialogQueue()
  const searchKey = ref('')
  const sessionList = ref([])
  const selectedSession = ref(null)

  // 动作
  async function updateSessionList() {
    let originSelectedSession = selectedSession.value
    const list = await agencyAsync.getFilteredSessionList() ?? []
    sessionList.value = list.map(id => id.toString())
    selectedSession.value = sessionList.value.includes(originSelectedSession) ? originSelectedSession : sessionList.value[0]
  }

  async function initialize() {
    searchKey.value = await agencyAsync.getSessionSearchKey()
    await updateSessionList()
  }

  async function handleSearchKeyChange() {
    await agencyAsync.setSessionSearchKeyword(searchKey.value)
    await updateSessionList()
  }

  async function editSession() {
    if (selectedSession.value) {
      await sessionEditorStore.show(new AppoxSessionIdentifier(selectedSession.value))
      await updateSessionList()
    }
  }

  function show() {
    return dialogQueue.show({
      onLoaded: () => initialize()
    })
  }

  function hide() {
    dialogQueue.hide()
  }

  return {
    // 状态
    isVisible: dialogQueue.isVisible,
    searchKey,
    sessionList,
    selectedSession,
    // 动作
    handleSearchKeyChange,
    editSession,
    show,
    hide,
    getQueueLength: dialogQueue.getQueueLength.bind(dialogQueue),
    clearQueue: dialogQueue.clearQueue.bind(dialogQueue)
  }
}) 